import { NextResponse } from 'next/server';
import { verifyToken } from '@/utils/auth';
import UserModel from '@/models/user';

// GET 请求处理器 - 获取招聘公告统计信息
export async function GET(request: Request, { params }: { params: { id: string } }) {
  try {
    // 验证用户身份
    const authHeader = request.headers.get('authorization');
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return NextResponse.json({ error: '未授权' }, { status: 401 });
    }

    const token = authHeader.split(' ')[1];
    const payload = verifyToken(token);

    if (!payload || !payload.id) {
      return NextResponse.json({ error: '无效的令牌' }, { status: 401 });
    }

    const userId = payload.id;
    const jobPostId = parseInt(params.id);

    if (isNaN(jobPostId)) {
      return NextResponse.json({ error: '无效的招聘公告ID' }, { status: 400 });
    }

    // 首先验证这个招聘公告是否属于当前用户
    const [jobPosts] = await UserModel.query<any[]>(
      `SELECT id FROM job_positions WHERE id = ? AND created_by = ?`,
      [jobPostId, userId]
    );

    if (!jobPosts || jobPosts.length === 0) {
      return NextResponse.json({ error: '招聘公告不存在或您无权查看' }, { status: 404 });
    }

    // 获取简历统计信息
    const [stats] = await UserModel.query<any[]>(
      `SELECT 
         COUNT(*) as total_resumes,
         SUM(CASE WHEN is_read = 1 THEN 1 ELSE 0 END) as read_resumes,
         SUM(CASE WHEN is_read = 0 OR is_read IS NULL THEN 1 ELSE 0 END) as unread_resumes
       FROM resume_submissions 
       WHERE position_id = ?`,
      [jobPostId]
    );

    const statsResult = stats[0] || { total_resumes: 0, read_resumes: 0, unread_resumes: 0 };

    // 获取简历申请列表
    const [applications] = await UserModel.query<any[]>(
      `SELECT rs.id, rs.user_id, rs.gender, rs.phone, rs.email, rs.school, 
              rs.graduation_year, rs.position_intent, rs.resume_file, rs.is_read,
              DATE_FORMAT(rs.created_at, '%Y-%m-%d %H:%i:%s') as submitted_at,
              u.username as user_name, u.avatar as user_avatar
       FROM resume_submissions rs
       LEFT JOIN users u ON rs.user_id = u.id
       WHERE rs.position_id = ?
       ORDER BY rs.created_at DESC`,
      [jobPostId]
    );

    // 格式化申请列表
    const formattedApplications = applications.map(app => ({
      id: app.id,
      user_name: app.user_name || '未知用户',
      user_avatar: app.user_avatar || '',
      school: app.school,
      graduation_year: app.graduation_year,
      gender: app.gender,
      phone: app.phone,
      email: app.email,
      is_read: !!app.is_read, // 转换为布尔值
      submitted_at: app.submitted_at,
      resume_file: app.resume_file
    }));

    const result = {
      total_resumes: parseInt(statsResult.total_resumes) || 0,
      read_resumes: parseInt(statsResult.read_resumes) || 0,
      unread_resumes: parseInt(statsResult.unread_resumes) || 0,
      applications: formattedApplications
    };

    console.log(`获取招聘公告统计: 用户ID=${userId}, 公告ID=${jobPostId}, 简历数=${result.total_resumes}`);

    return NextResponse.json(result);
  } catch (error) {
    console.error('获取招聘公告统计失败:', error);
    return NextResponse.json(
      { error: `获取招聘公告统计失败: ${(error as Error).message}` },
      { status: 500 }
    );
  }
} 